'use strict';
const Package = require('@cli-dev/package')
const log = require("@cli-dev/log")
const path = require("path");
const cp = require('child_process')
const {exec:spawn} = require("@cli-dev/utils")
// const { spawn } = require('child_process');
// const   { getDefaultRegistry }  = require('@hx-cli-dev/get-npm-info')
/**
 * 执行动态加载init方法
 */

 const SETTINGS = {
    //  init: '@cli-dev/init' // cli-dev
    init: '@imooc-cli/init'
 }

 const CACHE_DIR = 'dependencies';


async function exec() {
    let targetPath = process.env.CLI_TARGET_PATH;
    const homePath = process.env.CLI_HOME_PATH
   
    log.verbose('targetPath88888', targetPath)
    log.verbose('homePath', homePath)
    const cmdObj = arguments[arguments.length -1]
    const cmdName = cmdObj.name()
    const packageName = SETTINGS[cmdName]
    // const packageVersion = 'latest'
    const packageVersion = '1.0.1'
    let storeDir = ''
    let pkg;
    if(!targetPath){
        // 读缓存
        targetPath = path.resolve(homePath, CACHE_DIR)
         storeDir = path.resolve(targetPath,'node_modules')
         log.verbose('targetPath',targetPath)
         log.verbose('storeDir',storeDir)
          pkg = new Package({
            targetPath,
            storeDir,
            packageName,
            packageVersion
        })
        log.verbose('await pkg.exists()',await pkg.exists())

         if(await pkg.exists()){
            // 更新package
            await pkg.update()
    
        }else {
            // 安装package
            await pkg.install()
        }
        // 生成缓存路径
    }else {
         pkg = new Package({
            targetPath,
            packageName,
            packageVersion
        })
        const rootFile = pkg.getRootFilepath();
        log.verbose('getRootFilepath',rootFile)
        if(rootFile){
            try{
             // 当前进程中调用
              // require(rootFile).call(null, Array.from(arguments));
            // 在node环境中调用
            const args = Array.from(arguments)
            let cmd = args[args.length - 1]
            let o = Object.create(null)
            Object.keys(cmd).forEach(key => {
                if(cmd.hasOwnProperty(key) && !key.startsWith('_') && key!== 'parent'){
                    o[key] = cmd[key]
                }
            })
            args[args.length -1] = o;
            let ops =  args[args.length -2] 
            // cp.spwan('cmd',['/c', 'node','-e', code]) // window环境
            const code = `require('${rootFile}').call(null, ${JSON.stringify(args)})`
            const child = spawn('node', ['-e', code], {
                cwd: process.cwd(),
                stdio:'inherit'// 将相应的 stdio 流传给父进程或从父进程传入,所以process.stderr的时候，错误会打印两份

            })
            child.on('error', e=> {
                log.error(e.message)
                process.exit(1)
            })
            child.on('exit', e => {
                log.verbose('命令执行成功:'+e);
                process.exit(e)
            })
            }catch(err){
                log.error(e.message)

            }
        }
    }
}

module.exports = exec;